# !/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:zzly
@file:serializers.py
@time:2020/09/08
"""
from rest_framework import serializers
from apps.product.models import Product, ProductParameter
from apps.system.models import Option
from apps.system.serializers import ImagesSerializer


class ProductAppSeializer(serializers.ModelSerializer):
    thumbnail = serializers.SerializerMethodField(read_only=True)
    tags = serializers.SerializerMethodField()

    def get_tags(self, obj):
        return obj.tags.split('|')

    def get_thumbnail(self, obj):
        if obj.thumbnail:
            return obj.thumbnail.get_url()
        return ''

    class Meta:
        model = Product
        fields = ('id', 'name', 'thumbnail', 'tags', 'category', 'new_price', 'old_price', 'is_recommend')


class CategoryProductSerializer(serializers.ModelSerializer):
    icon = serializers.SerializerMethodField()
    codeName = serializers.CharField(source='name', read_only=True)
    products = serializers.SerializerMethodField()

    def get_products(self, obj):
        return ProductAppSeializer(Product.objects.filter(category=obj, delete=False, status=Product.SHELVE),
                                   many=True).data

    def get_icon(self, obj):
        icon_arr = obj.icon.split('|')
        if len(icon_arr) > 1:
            return icon_arr
        return [obj.icon, ]

    # 系统分类下拉列表
    class Meta:
        model = Option
        fields = ('id', 'codeName', 'icon', 'products')


class ProductParameterAppSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductParameter
        fields = ('value', 'parameter')


class ProductDetailAppSeializer(serializers.ModelSerializer):
    images = serializers.SerializerMethodField()
    parameters = serializers.SerializerMethodField()

    def get_parameters(self, obj):
        return ProductParameterAppSerializer(obj.parameters, many=True).data

    def get_images(self, obj):
        return ImagesSerializer(obj.images.all(), many=True).data

    class Meta:
        model = Product
        fields = (
            'id', 'name', 'new_price', 'old_price', 'images', 'parameters')
